import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import * as fs from 'fs';
import * as yaml from 'js-yaml';
import * as _ from 'lodash';
import { join } from 'path';
import { DataSource, DataSourceOptions } from 'typeorm';

/**
 * 实体
 */
import { Student } from './src/student/entities/student.entity';
import { Department } from './src/department/entities/department.entity';
import { Major } from './src/major/entities/major.entity';
import { ClassInfo } from './src/class-info/entities/class-info.entity';
import { Teacher } from './src/teacher/entities/teacher.entity';
import { Course } from './src/course/entities/course.entity';
import { SystemUser } from './src/system-user/entities/system-user.entity';
import { LessonsSort } from './src/lessons-sort/entities/lessons-sort.entity';
import { Publicity } from './src/publicity/entities/publicity.entity';
import { StudentCourse } from './src/student-course/entities/student-course.entity';
import { Role } from './src/roles/entities/role.entity';
import { Menu } from './src/menus/entities/menu.entity';
import { ClassRoom } from './src/class-rooms/entities/class-room.entity';
import { TimeSlot } from './src/time-slots/entities/time-slot.entity';

const YAML_CONFIG_FILENAME = 'config.yml';

const YAML_CONFIG_NODE_ENV = `config.${
  process.env.NODE_ENV === 'production' ? 'production' : 'development'
}.yml`;

const config = yaml.load(
  fs.readFileSync(join('config', YAML_CONFIG_NODE_ENV), 'utf8'),
);

const envConfig = yaml.load(
  fs.readFileSync(join('config', YAML_CONFIG_FILENAME), 'utf8'),
);

const mySqlConfig = _.merge(config, envConfig);

export const connectionParams = {
  type: 'mysql', // 数据库类型
  host: mySqlConfig.db.mysql.host, // 域名
  port: mySqlConfig.db.mysql.prot, // 端口
  username: mySqlConfig.db.mysql.username, // 数据库名字
  password: mySqlConfig.db.mysql.password, // 数据库密码
  database: 'school', // 库名
  entities: [
    Student,
    Department,
    Major,
    ClassInfo,
    Teacher,
    Role,
    Course,
    SystemUser,
    LessonsSort,
    ClassRoom,
    Publicity,
    StudentCourse,
    Menu,
    TimeSlot,
  ], // 导入的实体(数据库模型)
  synchronize: true,
  // 日志等级
  logging: true, //['query', 'error'],
} as TypeOrmModuleOptions;

export default new DataSource({
  ...connectionParams,
  migrations: ['src/migrations/**'],
  subscribers: [],
} as DataSourceOptions);
